package com.fjec.devops.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjec.common.enums.EnumSysCode;
import com.fjec.common.exception.BizException;
import com.fjec.common.view.AnnexBizItem;
import com.fjec.devops.entity.InfoCooperator;
import com.fjec.devops.entity.InfoMarket;
import com.fjec.devops.feign.BaseClient;
import com.fjec.devops.feign.MarketClient;
import com.fjec.devops.feign.PaidClient;
import com.fjec.devops.service.IInfoCooperatorService;
import com.fjec.devops.service.MarketService;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
@Transactional(rollbackFor = Throwable.class)
public class MarketServiceImpl implements MarketService {

    @Autowired
    private MarketClient marketClient;

    @Autowired
    private BaseClient baseClient;

    @Autowired
    private IInfoCooperatorService infoCooperatorService;

    @Autowired
    private PaidClient paidClient;

    @Override
    public Map<String, Object> listMarkets(Page page) {
        return marketClient.getMarkets((int)page.getCurrent(), (int)page.getSize());
    }

    @Override
    public void saveOrUpdate(InfoMarket infoMarket, String markPic, Long markPicId, String markMapPic, Long markMapPicId) {
        int result = marketClient.saveOrUpdate(infoMarket, markPic, markMapPic);
        if (result != 0)
            throw new BizException(EnumSysCode.ERR_3001.getCode(), EnumSysCode.ERR_3001.getMsg());

        List<AnnexBizItem> annexBizItems = new ArrayList<>();
        if (markPicId != null) {
            // rpc set annex enable
            AnnexBizItem bizItem = new AnnexBizItem();
            bizItem.setAnnexId(markPicId);
            bizItem.setBizId(infoMarket.getId());
            bizItem.setBizType(3);
            annexBizItems.add(bizItem);
        }
        if (markMapPicId != null) {
            // rpc set annex enable
            AnnexBizItem bizItem = new AnnexBizItem();
            bizItem.setAnnexId(markMapPicId);
            bizItem.setBizId(infoMarket.getId());
            bizItem.setBizType(13);
            annexBizItems.add(bizItem);
        }

        if (annexBizItems.size() > 0) {
            int count = 0;
            count = baseClient.enableAnnexStatus(annexBizItems);
            if (count != annexBizItems.size())
                throw new BizException(EnumSysCode.ERR_3001.getCode(), EnumSysCode.ERR_3001.getMsg());
        }


    }

    @Override
    public Map<String, Object> getByCode(int markCode) {
        return marketClient.getMarketByMarkCode(markCode);
    }

    @Override
    public Map<String, Object> getDepoInfoByConditions(Integer searchBy, String title, Integer busiType, Integer markCode, Integer depoStatus, Integer timedBy, String startTime, String endTime, Page page) {
        return marketClient.getDepoInfoByConditions(searchBy, title, busiType, markCode, depoStatus, timedBy, startTime, endTime, page.getCurrent(), page.getSize());
    }

    @Override
    public Map<String, Object> getBusinessesOfAllTypesByConditions(Integer searchBy, String title, Integer busiType, Integer markCode, String startTime, String endTime, Page page) {
        Map<String, Object> result = marketClient.getBusinessesOfAllTypesByConditions(searchBy, title, busiType,
                                                            markCode, startTime, endTime, page.getCurrent(), page.getSize());
        List<Map<String, Object>> data = (List<Map<String, Object>>) result.get("data");

        if (data.size() == 0)
            return result;

        List<Long> coopIds = new ArrayList<>();
        data.forEach(m -> {
            Long coopId = MapUtils.getLong(m, "coopId");
            coopIds.add(coopId);
        });
        List<InfoCooperator> cooperators = infoCooperatorService
                .list(new QueryWrapper<InfoCooperator>().in("Id", coopIds));
        data.forEach(m -> {
            Long coopId = MapUtils.getLong(m, "coopId");
            String coopName = "";
            Integer coopCode = 0;
            Optional<InfoCooperator> opt = cooperators.stream().filter(c -> c.getId().equals(coopId)).findFirst();
            if (opt.isPresent()) {
                InfoCooperator c = opt.get();
                coopName = c.getName();
                coopCode = c.getCode();
            }
            m.put("coopName", coopName);
            m.put("coopId", coopCode);
        });

        return result;
    }

    @Override
    public Map<String, Object> getOrdersByConditions(Integer searchBy, String title, Integer busiType, Integer markCode, Integer orderType, Integer orderStatus, String startTime, String endTime, Page page) {
        return marketClient.getOrdersByConditions(searchBy, title, busiType, markCode, orderType, orderStatus, startTime, endTime, page.getCurrent(), page.getSize());
    }

    @Override
    public Map<String, Object> getOrdersByBusiId(Long busiId, Long page, Long limit) {
        return marketClient.getOrdersByBusiId(busiId, page, limit);
    }

    @Override
    public Map<String, Object> getOrderDetailById(Long id) {
        return marketClient.getOrderDetailById(id);
    }

    @Override
    public Map<String, Object> getBusinessInfo(Long busiId, Integer busiType) {
        Map<String, Object> result = marketClient.getBusinessInfo(busiId, busiType);
        Integer bizType;
        if (busiType == 2)
            bizType = 102;
        else
            bizType = 101;
        String annexPicBase64 = baseClient.getCredentialPicId(busiId, bizType);
        result.put("credentialPic", annexPicBase64.substring(1, annexPicBase64.length() - 1));
        return result;
    }

    @Override
    public Map<String, Object> getTradingsByConditions(Integer searchBy, String title, Integer orderType, Integer sellerType, Integer buyerType, Page page) {
        return marketClient.getTradingsByConditions(searchBy, title, orderType, sellerType, buyerType, page.getCurrent(), page.getSize());
    }

    @Override
    public Map<String, Object> getOrderComplaintsByConditions(Integer searchBy, String title, Integer busiType, Integer markCode, Integer orderType, Integer orderStatus, String startTime, String endTime, Page page) {
        return marketClient.getOrderComplaintsByConditions(searchBy, title, busiType, markCode, orderType, orderStatus, startTime, endTime, page.getCurrent(), page.getSize());
    }

    @Override
    public int handleComplaint(Long orderId, Long subOrderId, Long complaintId, Integer handleType, String amount, String complaintText) {
        return marketClient.handleComplaint(orderId, subOrderId, complaintId, handleType, amount, complaintText);
    }

    @Override
    public Map<String, Object> getAccountInfo(Long busiId) {
        return marketClient.getAccountInfo(busiId);
    }

    @Override
    public int refundDeposit(Long busiId, Integer busiType) {
        int code = marketClient.refundDeposit(busiId, busiType);
        return code;
    }
}
